import _ from 'lodash';
import React, {useEffect, useState} from 'react';
import {Checkbox} from 'acud';

const CheckboxGroup = Checkbox.Group;

interface Props {
    form: any;
    name: any;
    defaultOptions: string[];
    options: string[];
}
export const CheckGroup:React.FC<Props> = ({form, name, options, defaultOptions}) => {
    const [checkedList, setCheckedList] = useState(defaultOptions);
    const [indeterminate, setIndeterminate] = useState(true);
    const [checkAll, setCheckAll] = useState(false);

    const onChange = (list: any) => {
        setCheckedList(list);
        setIndeterminate(!!list.length && list.length < options.length);
        setCheckAll(list.length === options.length);
    };

    useEffect(() => {
        if (_.isEqual(checkedList, options)) {
            setCheckAll(true);
            setIndeterminate(false);            
        }
        form.setFieldValue(name, checkedList);
    }, [checkedList]);

    const onCheckAllChange = (e: any) => {
        setCheckedList(e.target.checked ? options : []);
        setIndeterminate(false);
        setCheckAll(e.target.checked);
    };

    return (
        <div style={{display: 'flex'}}>
            <Checkbox
                indeterminate={indeterminate}
                onChange={onCheckAllChange}
                checked={checkAll}
                style={{marginRight: 16}}
            >
                全选
            </Checkbox>
            <CheckboxGroup options={options} value={checkedList} onChange={onChange} />
        </div>
    );
};
